package com.hntky.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hntky.controller.dto.UserDTO;
import com.hntky.entity.User;
import com.hntky.exception.ServiceException;
import com.hntky.service.UserService;
import com.hntky.mapper.UserMapper;
import com.hntky.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
* @author admin
* @description 针对表【t_user】的数据库操作Service实现
* @createDate 2023-05-03 17:28:35
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Autowired
    private UserMapper mapper;

    /**
     * 用户登录
     * @param userDTO
     * @return
     */
    @Override
    public UserDTO login(UserDTO userDTO) {
        User user = getUserInfo(userDTO);
        // 查出数据且不为空
        if(user != null) {
            // 将user对象克隆到userDTO中
            BeanUtil.copyProperties(user, userDTO, true);
            // 设置token
            String token = TokenUtils.genToken(user.getId().toString(), user.getPassword());
            userDTO.setToken(token);
            return userDTO;
        } else {
            // 抛异常
            throw new ServiceException("600", "用户名或密码错误");
        }
    }

    /**
     * 新增用户
     * @param userDTO
     * @return
     */
    @Override
    public int insertUser(UserDTO userDTO) {
        User user = getUserInfo(userDTO);
        if(user == null) {
            user = new User();
            BeanUtil.copyProperties(userDTO, user, true);
            return mapper.insert(user);
        } else {
            throw new ServiceException("600", "用户已存在");
        }
    }

    @Override
    public int updateUser(UserDTO userDTO) {
        User user = getUserInfo(userDTO);
        if(user != null) {
            user = new User();
            BeanUtil.copyProperties(userDTO, user, true);
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("username", userDTO.getUsername());
            return mapper.update(user, queryWrapper);
        } else {
            throw new ServiceException("600", "用户修改失败");
        }
    }

    public User getUserInfo(UserDTO userDTO) {
        // 从数据库中查询数据
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.eq("password", userDTO.getPassword());
        queryWrapper.eq("username", userDTO.getUsername());
        User user = null;
        // 如果数据库查出多条数据则抛异常
        try {
            user = mapper.selectOne(queryWrapper);
        } catch (Exception e) {
            throw new ServiceException("500", "系统错误");
        }
        return user;
    }

}




